/*
 * @(#)CheckAndCreateBinlogEvent.java   1.0  2021年11月18日
 * 
 * Copyright (c)	2014-2020. All Rights Reserved.	GuangZhou hhmk Technology Company LTD.
 */
package com.swift.dts.init;

import java.util.LinkedList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.swift.core.env.ConfigInterface.ChangeConfigKV;
import com.swift.core.env.ConfigInterface.ConfigChangeListener;
import com.swift.dts.init.core.DbChange;
import com.swift.dts.loadconfig.model.DtsDataBase;
import com.swift.dts.source.canal.CanalDtsServer;
import com.swift.util.type.TypeUtil;

/**
 * 添加说明 
 * @author zhengjiajin
 * @version 1.0 2021年11月18日
 */
@Component
@Order
public class CheckAndCreateBinlogEvent extends DbChange implements ConfigChangeListener<DtsDataBase> {

    @Autowired
    private CanalDtsServer canalDtsServer;
    /** 
     * @see com.swift.core.env.ConfigInterface.ConfigChangeListener#listener(java.util.List)
     */
    @Override
    public void listener(List<ChangeConfigKV<DtsDataBase>> list) {
        if(TypeUtil.isNull(list)) return;
        List<ChangeConfigKV<String>> changeList = new LinkedList<>();
        for(ChangeConfigKV<DtsDataBase> dbchange:list) {
            DtsDataBase old = dbchange.getOldConfig();
            DtsDataBase ne = dbchange.getNewConfig();
            if(!checkAddressChange(old, ne) && !checkSourceChange(old, ne)) continue;
            
            boolean insert = false;
            ChangeConfigKV<String> changeDestination = new ChangeConfigKV<>();
            if(dbchange.getNewConfig()!=null) {
                if(dbchange.getNewConfig().getIsSource()) {
                    changeDestination.setNewConfig(dbchange.getNewConfig().getKey());
                    insert = true;
                }
            }
            if(dbchange.getOldConfig()!=null) {
                if(dbchange.getOldConfig().getIsSource()) {
                    changeDestination.setOldConfig(dbchange.getOldConfig().getKey());
                    insert = true;
                }
            }
            if(insert) changeList.add(changeDestination);
            
        }
        if(TypeUtil.isNull(changeList)) return;
        canalDtsServer.restart(changeList);
    }

}
